package com.trip.driver.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trip.common.dto.DriverOrderSearchDto;
import com.trip.common.dto.LoginDto;
import com.trip.common.dto.UpdateDriverDto;
import com.trip.common.entity.Driver;
import com.trip.common.po.Comment;
import com.trip.common.po.TripOrder;
import com.trip.common.util.PasswordEncode;
import com.trip.common.util.RedisUtil;
import com.trip.common.util.SendEmailAuthUtil;
import com.trip.common.util.TokenUtil;
import com.trip.common.vo.DataDictionary;
import com.trip.common.vo.MyResultMap;
import com.trip.common.vo.Result;
import com.trip.driver.mapper.DriverMapper;
import com.trip.driver.service.DriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hr
 * @since 2024-09-05
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements DriverService {
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SendEmailAuthUtil sendEmailAuthUtil;
    @Autowired
    private PasswordEncode passwordEncode;

    @Override
    public Result loginByAccount(LoginDto loginDto) {
        Driver driver = driverMapper.loginByAccount(loginDto);
        if (!ObjectUtils.isEmpty(driver)){
//            passwordEncode.matches(driver.getPassword(),loginDto.getPassword())
            if (driver.getPassword().equals(loginDto.getPassword())){
                return setToken(driver);
            }else{
                return Result.error(DataDictionary.FAIL,"密码错误");
            }
        }else {
            return Result.error(DataDictionary.FAIL,"该用户不存在");
        }
    }

    @Override
    public Result loginByEmail(LoginDto loginDto) {
        //判断当前用户是否已注册
        Driver driver = driverMapper.loginByAccount(loginDto);
        if (ObjectUtils.isEmpty(driver)){
            return Result.error(DataDictionary.NO_REG,"当前用户未注册");
        }

        //判断验证码是否正确
        int code = sendEmailAuthUtil.checkCode(loginDto);

        //验证码过期或不存在
        if (code == 0){
            return Result.error(DataDictionary.NO_DATA,"验证码已过期");
        }else if (code == 1){
            //校验通过
            return setToken(driver);
        }else if (code == 2){
            //验证码错误
            return Result.error(DataDictionary.FAIL,"验证码错误");
        }else {
            return Result.error(DataDictionary.FAIL,"");
        }
    }

    @Override
    public void sendEmail(String email) {
        sendEmailAuthUtil.send(email);
    }

    //获取司机当前钱包余额
    @Override
    public BigDecimal getMyMoney(String token) {
        String driver_id = tokenUtil.decodeGetID(token);
        BigDecimal myMoney = driverMapper.getMyMoney(driver_id);
        return myMoney;
    }

    //获取司机今日公里数
    @Override
    public String getMyDistance(String token) {
        String driver_id = tokenUtil.decodeGetID(token);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(System.currentTimeMillis());
        String myDistance = driverMapper.getMyDistance(driver_id,format);
        return myDistance;
    }

    //获取司机今日订单数
    @Override
    public String getMyOrderNum(String token) {
        String driver_id = tokenUtil.decodeGetID(token);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(System.currentTimeMillis());
        String myOrderNum = driverMapper.getMyOrderNum(driver_id,format);
        return myOrderNum;
    }

    //获取司机今日流水
    @Override
    public String getToDayPrice(String token) {
        String driver_id = tokenUtil.decodeGetID(token);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(System.currentTimeMillis());
        String toDayPrice = driverMapper.getToDayPrice(driver_id,format);
        return toDayPrice;
    }

    @Override
    public Result getMyOrderDetail(DriverOrderSearchDto driverOrderSearchDto) {
        String driver_id = tokenUtil.decodeGetID(driverOrderSearchDto.getToken());
        driverOrderSearchDto.setToken(driver_id);

//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String format = formatter.format(System.currentTimeMillis());
        List<TripOrder> myOrderDetail = driverMapper.getMyOrderDetail(driverOrderSearchDto);
        HashMap<String, Object> myResultMap = MyResultMap.getMyResultMap();
        myResultMap.put("data",myOrderDetail);
        if (myOrderDetail.size() > 0){
            return Result.ok("成功",myResultMap);
        }else {
            return Result.ok("为空",myResultMap);
        }
    }

    @Override
    public Result getDriverInfo(String token) {
        String driver_id = tokenUtil.decodeGetID(token);
        Driver driverInfo = driverMapper.getDriverInfo(driver_id);
        if (driverInfo != null){
            HashMap<String, Object> myResultMap = MyResultMap.getMyResultMap();
            myResultMap.put("data",driverInfo);
            return Result.ok("获取信息成功",myResultMap);
        }else {
            return Result.error(DataDictionary.FAIL,"获取信息失败");
        }
    }

    @Override
    public Result getOrderDetailByID(String order_id) {
        TripOrder orderDetailByID = driverMapper.getOrderDetailByID(order_id);
        if (orderDetailByID != null){
            HashMap<String, Object> myResultMap = MyResultMap.getMyResultMap();
            myResultMap.put("data",orderDetailByID);
            return Result.ok("获取信息成功",myResultMap);
        }else {
            return Result.error(DataDictionary.FAIL,"获取信息失败");
        }
    }

    @Override
    public Result unpaidOrders(String order_id) {
        TripOrder orderDetailByID = driverMapper.getOrderDetailByID(order_id);
        boolean flag = sendEmailAuthUtil.unpaidOrders(orderDetailByID.getUserId().getEmail(), orderDetailByID.getOrderNum(), orderDetailByID.getCreateTime(),
                orderDetailByID.getOrderInfoId().getStartPosition(), orderDetailByID.getOrderInfoId().getPracticalPurpose());
        if (flag){
            return Result.ok("邮件已发送");
        }else {
            return Result.error("邮件发送失败");
        }
    }

    @Override
    public Result getCommentByID(String token) {
        String driver_id = tokenUtil.decodeGetID(token);
        List<Comment> commentByID = driverMapper.getCommentByID(driver_id);
        if (commentByID.size() > 0){
            HashMap<String, Object> myResultMap = MyResultMap.getMyResultMap();
            myResultMap.put("data",commentByID);
            return Result.ok("获取信息成功",myResultMap);
        }else {
            return Result.error(DataDictionary.FAIL,"获取信息失败");
        }
    }

    @Override
    public Result updateDriverInfo(UpdateDriverDto updateDriverDto) {
        LoginDto loginDto = new LoginDto();
        loginDto.setEmail(updateDriverDto.getEmail());
        loginDto.setPass_code(updateDriverDto.getCode());
        int flag = sendEmailAuthUtil.checkCode(loginDto);
        //验证码过期或不存在
        if (flag == 0){
            return Result.error(DataDictionary.NO_DATA,"验证码已过期");
        }else if (flag == 1){
            String driverId = tokenUtil.decodeGetID(updateDriverDto.getToken());
            updateDriverDto.setDriverId(driverId);
            int i = driverMapper.updateDriverInfo(updateDriverDto);
            if (i > 0){
                return Result.ok("信息修改成功");
            }else {
                return Result.error("信息修改失败");
            }
        }else if (flag == 2){
            //验证码错误
            return Result.error(DataDictionary.FAIL,"验证码错误");
        }else {
            return Result.error(DataDictionary.FAIL,"");
        }

    }


    @Override
    public Result resetPWD(UpdateDriverDto updateDriverDto) {
        LoginDto loginDto = new LoginDto();
        loginDto.setPass_code(updateDriverDto.getCode());
        int code = sendEmailAuthUtil.checkCode(loginDto);
        if (code == 0){
            return Result.error(DataDictionary.NO_DATA,"验证码已过期");
        }else if (code == 1){
            String driver_id = tokenUtil.decodeGetID(updateDriverDto.getToken());
            String encode = passwordEncode.encode("123456");
            updateDriverDto.setDriverId(driver_id);
            updateDriverDto.setCode(encode);
            int i = driverMapper.resetPWD(updateDriverDto);
            if (i > 0){
                return Result.ok("密码重置成功");
            }else {
                return Result.error("密码重置失败");
            }
        }else if (code == 2){
            //验证码错误
            return Result.error(DataDictionary.FAIL,"验证码错误");
        }else {
            return Result.error(DataDictionary.FAIL,"");
        }

    }

    private Result setToken(Driver driver){
        String token = tokenUtil.createToken(String.valueOf(driver.getDriverId()),driver.getUserName(),"driver");
        redisUtil.set(token,driver.getUserName());
        //登录成功半个小时后失效
        redisUtil.setExpire(token,60*30);
        HashMap<String, Object> myResultMap = MyResultMap.getMyResultMap();
        myResultMap.put("userName",driver.getUserName());
        myResultMap.put("userId",driver.getDriverId());
        myResultMap.put("avatar",driver.getAvatar());
        myResultMap.put("token",token);
        return Result.ok("登录成功，页面跳转中",myResultMap);
    }
}
